//pragma JS
if(manager.readFile('./plugins/BlocklyNukkit/NGuild/Config.yml') === "FILE NOT FOUND") {
	manager.writeFile("./plugins/BlocklyNukkit/NGuild/Config.yml", manager.JSONtoYAML(JSON.stringify({
		language: 'chs',
		version: '2021-04-04',
		pageItems: 15,
		CreatePrice: 1e5,
		JoinCooling: 86400,
		SaveDataMode: 0,
		GuildChat: true,
		GuildBase: true,
		GuildShop: false,
		GuildSign: true,
		GuildImpeach: true,
		GuildEventsLength: 100,
		GuildContriMax: 3e4,
		GuildBaseConfig: {
			Change: 10000,
			Use: 100
		},
		GuildImpeachConfig: {
			AllowTime: 24*7,//h, 最长不活跃时间(满足即可弹劾)
			HoldTime: 24,//h, 弹劾期间会长保持时间(如时间内仍未活跃则更改会长)
		},
		GuildChatConfig: {
			style: "[公会频道] {post}§7{name}§r: {msg}"
		},
		GuildName: {
			LengthMin: 2,
			LengthMax: 6,
			Regex: "^[\u4e00-\u9fa5_a-zA-Z0-9]+$"
		},
		GuildGrade: {
			UpgradeNeed: "Math.pow({level}+1, 2)*10000",// 需求经济
			MaxMember: "({level}+1)*5",// 最大人数
			BaseUseCount: "({level}+1)*100"// 基地可使用次数
		},
		Authority: {
			setSignReward: 0,
			setBase: 1,
			upgradeGuild: 2,
			agreeApply: 2,
			setPVP: 3,
			setIntroduction: 1
		},
		MailTips: {
			Applicant: 2,
			Exit: 3,
			Contri: 2
		},
		Tips: {
			NoneGuild: "无公会",
			NotAllowGuildPVP: "\n\n[NGuild] 该公会不允许成员间PVP.",
			Online: ["§a[在线] §r", "§7[离线] §r"],
			SignStatus: ["已签到", "§6未签到"]
		},
		Posts: ["会长", "副会长", "元老", "精英", "成员"]
	})));
}
isExistDir("./plugins/BlocklyNukkit/NGuild/GuildData");// 创建目录
isExistDir("./plugins/BlocklyNukkit/NGuild/GuildEvent");// 创建目录
manager.createConfig(manager.getFile("NGuild", "PlayerData.yml"), 2);
manager.createConfig(manager.getFile("NGuild", "GuildRankData.json"), 2);
var Config = JSON.parse(manager.YAMLtoJSON(manager.readFile("./plugins/BlocklyNukkit/NGuild/Config.yml")));
var PlayerData = JSON.parse(manager.YAMLtoJSON(manager.readFile("./plugins/BlocklyNukkit/NGuild/PlayerData.yml")));
var GuildRankData = JSON.parse(manager.readFile("./plugins/BlocklyNukkit/NGuild/GuildRankData.json"));
var GuildList = getFileList("./plugins/BlocklyNukkit/NGuild/GuildData");
var TempVar = {};
if(!Config.MailTips) {
	Config.MailTips = {
		Applicant: 2,
		Exit: 3,
		Contri: 2
	}
	manager.writeFile("./plugins/BlocklyNukkit/NGuild/Config.yml", manager.JSONtoYAML(JSON.stringify(Config)));
}
if(!GuildRankData.Fund) GuildRankData.Fund = [];
if(!GuildRankData.Grade) GuildRankData.Grade = [];
if(!GuildRankData.Member) GuildRankData.Member = [];
manager.createCommand("公会", "打开公会UI", 'NGuildFuncCore');
//manager.createCommand("管理 [公会]", "管理员管理命令", 'NGuildFuncCore');
function NGuildFuncCore(sender, args){
	if(!PlayerData[sender.name]) {
		PlayerData[sender.name] = {
			Guild: false,
			GuildChat: false,
			Post: -1,
			ContriPoint: 0,
			SignData: ["2020-10-16", 0, 0],
			JoinTime: "2020-09-28 00:00:00", 
			JoinGameTime: "2020-10-12 00:00:00", 
			QuitGameTime: "2020-10-12 00:00:00"
		};
		SavePlayerData();
	}
	if(args.length === 0) {
		sendNGuildMainWin(sender.getPlayer());
	}
}
function sendNGuildMainWin(player){
	let win = window.getSimpleWindowBuilder('NGuild', ''); //简单的按钮窗口
	if(PlayerData[player.name].Guild === false) {
		win.buildButton('创建公会', '');
		win.buildButton('加入公会', '');
	} else {
		win.buildButton('我的公会', '');
		win.buildButton('退出公会', '');
	}
	win.buildButton('公会基金排行榜', '');
	win.buildButton('公会等级排行榜', '');
	win.buildButton('公会人数排行榜', '');
	win.showToPlayer(player, 'NGuildMainWinCallback');
}
function NGuildMainWinCallback(event){
	let player = event.getPlayer();
	let str = window.getEventResponseText(event);
	switch (str) {
		case '我的公会':
			sendMyGuildWin(player);
			break;
		case '创建公会':
			sendCreateGuildWin(player);
			break;
		case '加入公会':
			sendJoinGuildWin(player, 0);
			break;
		case '退出公会':
			sendQuitGuildWin(player);
			break;
		case '公会基金排行榜':
			sendFundList(player, 0);
			break;
		case '公会等级排行榜':
			sendGradeList(player, 0);
		break;
		case '公会人数排行榜':
			sendMemberList(player, 0);
		break;
		default:
			logger.warning("公会主界面未知按钮: "+str);
	}
}

//Master Window Functions
function sendMyGuildWin(player){
	let data = PlayerData[player.name];
	let GuildName = PlayerData[player.name].Guild;
	let Guild = isExistGuildData(GuildName);
	if(data.Post == -1) return player.sendMessage("[NGuild] §c你没有加入任何公会");
	let win = window.getSimpleWindowBuilder('我的公会', '公会名: '+GuildName+
	  '\n公会等级: '+Guild.Grade+
	  '\n公会基金: '+Guild.Fund+
	  '\n公会人数: '+Guild.CurrentMember+'/'+Guild.MaxMember+
	  '\n我的职务: '+Config.Posts[data.Post]+
	  '\n公会PVP: '+(Guild.GuildPVP ? "§6开启§f" : "§f关闭"));//简单的按钮窗口
	win.buildButton('公会贡献', '');
	win.buildButton('公会签到', '');
	if(Config.GuildShop) win.buildButton('公会商店', '');
	win.buildButton('公会事件', '');
	win.buildButton('公会成员', '');
	if(Config.GuildImpeach) win.buildButton('弹劾会长', '');
	if(data.Post <= Config.Authority.setPVP) {
		if(Guild.GuildPVP) {
			win.buildButton('关闭公会PVP', '');
		} else {
			win.buildButton('开启公会PVP', '');
		}
	}
	if(Config.GuildBase) win.buildButton('传送公会基地', '');
	if(Config.GuildChat) if(data.GuildChat === false) win.buildButton('开启公会聊天', '');
	if(data.GuildChat === true) win.buildButton('关闭公会聊天', '');
	if(data.Post <= Config.Authority.agreeApply) win.buildButton('申请列表', '');
	if(data.Post <= Config.Authority.upgradeGuild) win.buildButton('升级公会', '');
	if(data.Post <= 1) win.buildButton('移除公会成员', '');
	if(data.Post <= Config.Authority.setIntroduction) win.buildButton('设置公会简介', '');
	if(data.Post <= Config.Authority.setBase) win.buildButton('设置公会基地', '');
	if(data.Post <= Config.Authority.setSignReward) win.buildButton('设置签到奖励', '');
	if(data.Post <= Config.Posts.length-3) win.buildButton('设置公会职务', '');
	if(data.Post <= 1) win.buildButton('设置邮件提醒', '');
	win.buildButton(' §r返回 ', '');
	win.showToPlayer(player, 'MyGuildWinCallback');
}
function sendCreateGuildWin(player){
	let win = window.getCustomWindowBuilder('创建公会'); //创建自定义窗口
	win.buildLabel("建立公会需要: §l§6"+Config.CreatePrice + "§r金币\n\n" +
	  "# 公会名规则 #\n最小长度: "+Config.GuildName.LengthMin+
	  "\n最大长度: "+Config.GuildName.LengthMax+
	  "\n正则校验: "+Config.GuildName.Regex);
	win.buildInput('公会名', '填写你想要创建的公会名', '');
	win.showToPlayer(player, 'CreateGuildWinCallback');
}
function sendJoinGuildWin(player, page){
	let nextpage = page+1;
	let win = window.getSimpleWindowBuilder('公会列表 - '+page, '');
	win.buildButton(' §c搜索公会 ', '');
	for(let i = page*Config.pageItems; i<nextpage*Config.pageItems; i++) {
		if(i >= GuildList.length) break;
		let file = GuildList[i];
		win.buildButton(file.getName().split(".yml")[0], "");
	}
	if(page*Config.pageItems != 0) win.buildButton(' §r上一页 ', '');
	if(nextpage*Config.pageItems < GuildList.length) win.buildButton(' §r下一页 ', '');
	if(!TempVar[player.name]) TempVar[player.name] = {};
	TempVar[player.name].joinFromPage = page;
	win.showToPlayer(player, 'JoinGuildWinCallback');
}
function sendQuitGuildWin(player){
	let win = window.getCustomWindowBuilder('退出公会 - 最后一次确认操作');
	let str1 = "1. 退出后您将不再享受该公会福利\n2. 退出后24h内无法申请加入任何公会";
	let str2 = "取消";
	switch (PlayerData[player.name].Post) {
		case 0:
			str1 += "\n\n§c您是会长，退出后公会将会自动解散。\n建议在转让会长后退出。";
			str2 += ";转让;解散";
			break;
		default:
			str2 += ";退出";
	}
	win.buildLabel(str1);
	win.buildStepSlider("请选择", str2, 0);
	win.showToPlayer(player, 'QuitGuildWinCallback');
}
//RankWin - Start
function sendFundList(player, page){
	let nextpage = page+1;
	let data = GuildRankData.Fund;
	let win = window.getSimpleWindowBuilder('公会基金排行榜 - '+page, '');
	for(let i = page*Config.pageItems; i<nextpage*Config.pageItems; i++) {
		if(i >= data.length) break;
		win.buildButton(data[i].name+"\n基金: "+data[i].value, "");
	}
	if(page*Config.pageItems != 0) win.buildButton(' §r上一页 ', '');
	if(nextpage*Config.pageItems < GuildList.length) win.buildButton(' §r下一页 ', '');
	win.buildButton(' §r返回 ', '');
	if(!TempVar[player.name]) TempVar[player.name] = {};
	TempVar[player.name].RankFromPage = page;
	win.showToPlayer(player, 'FundListWinCallback');
}
function sendGradeList(player, page){
	let nextpage = page+1;
	let data = GuildRankData.Grade;
	let win = window.getSimpleWindowBuilder('公会等级排行榜 - '+page, '');
	for(let i = page*Config.pageItems; i<nextpage*Config.pageItems; i++) {
		if(i >= data.length) break;
		win.buildButton(data[i].name+"\n等级: "+data[i].value, "");
	}
	if(page*Config.pageItems != 0) win.buildButton(' §r上一页 ', '');
	if(nextpage*Config.pageItems < GuildList.length) win.buildButton(' §r下一页 ', '');
	win.buildButton(' §r返回 ', '');
	if(!TempVar[player.name]) TempVar[player.name] = {};
	TempVar[player.name].RankFromPage = page;
	win.showToPlayer(player, 'GradeListWinCallback');
}
function sendMemberList(player, page){
	let nextpage = page+1;
	let data = GuildRankData.Member;
	let win = window.getSimpleWindowBuilder('公会人数排行榜 - '+page, '');
	for(let i = page*Config.pageItems; i<nextpage*Config.pageItems; i++) {
		if(i >= data.length) break;
		win.buildButton(data[i].name+"\n人数: "+data[i].value, "");
	}
	if(page*Config.pageItems != 0) win.buildButton(' §r上一页 ', '');
	if(nextpage*Config.pageItems < GuildList.length) win.buildButton(' §r下一页 ', '');
	win.buildButton(' §r返回 ', '');
	if(!TempVar[player.name]) TempVar[player.name] = {};
	TempVar[player.name].RankFromPage = page;
	win.showToPlayer(player, 'MemberListWinCallback');
}
function FundListWinCallback(event){
	let player = event.getPlayer();
	let button = window.getEventResponseText(event).split("\n")[0];
	switch (button) {
		case ' §r上一页 ':
			sendFundList(player, TempVar[player.name].RankFromPage -1);
			break;
		case ' §r下一页 ':
			sendFundList(player, TempVar[player.name].RankFromPage +1);
			break;
		case ' §r返回 ':
			sendNGuildMainWin(player);
			break;
		default: {
			sendGuildDetailsWin(player, false, button);
		}
	}
}
function GradeListWinCallback(event){
	let player = event.getPlayer();
	let button = window.getEventResponseText(event).split("\n")[0];
	switch (button) {
		case ' §r上一页 ':
			sendGradeList(player, TempVar[player.name].RankFromPage -1);
			break;
		case ' §r下一页 ':
			sendGradeList(player, TempVar[player.name].RankFromPage +1);
			break;
		case ' §r返回 ':
			sendNGuildMainWin(player);
			break;
		default: {
			sendGuildDetailsWin(player, false, button);
		}
	}
}
function MemberListWinCallback(event){
	let player = event.getPlayer();
	let button = window.getEventResponseText(event).split("\n")[0];
	switch (button) {
		case ' §r上一页 ':
			sendMemberList(player, TempVar[player.name].RankFromPage -1);
			break;
		case ' §r下一页 ':
			sendMemberList(player, TempVar[player.name].RankFromPage +1);
			break;
		case ' §r返回 ':
			sendNGuildMainWin(player);
			break;
		default: {
			sendGuildDetailsWin(player, false, button);
		}
	}
}
// RankWin - End
function sendSearchGuildWin(player){
	let win = window.getCustomWindowBuilder('搜索公会');
	win.buildInput('输入框', '公会名');
	win.showToPlayer(player, 'SearchGuildWinCallback');
}
function sendGuildDetailsWin(player, res, GuildName){
	if(res == false) res = isExistGuildData(GuildName);
	let win = window.getCustomWindowBuilder('公会详细 - '+GuildName); //创建自定义窗口
	win.buildLabel("本公会由"+res.Creator+"创建于"+res.CreateTime+
	"\n\n现任会长: "+res.Posts[0]+
	"\n公会简介: "+res.Introduction+"§r"+
	"\n公会人数: "+res.CurrentMember+"/"+res.MaxMember);
	if(PlayerData[player.name].Guild === false) {
		TempVar[player.name].joinGuildName = GuildName;
		win.buildStepSlider("请选择", "取消;申请加入", 1);
	} else {
		win.buildStepSlider("请选择", "取消;我的工会", 0);
	}
	win.showToPlayer(player, 'GuildDetailsWinCallback');
}
function sendSetGuildMailTipsWin(player){
	let data = PlayerData[player.name];
	let GuildName = PlayerData[player.name].Guild;
	let Guild = isExistGuildData(GuildName);
	if(!Guild.MailTips) {
		Guild.MailTips = {
			switch: true,
			Applicant: true,
			Exit: true,
			Contri: true
		}
		SaveGuildData(GuildName, Guild);
	}
	let lang = {
		switch: "总开关",
		Applicant: "申请",
		Exit: "退出",
		Contri: "贡献"
	}
	let win = window.getCustomWindowBuilder("修改邮件提醒");
	for (i in Guild.MailTips) {
		win.buildToggle(lang[i], Guild.MailTips[i]);
	}
	win.showToPlayer(player, 'SetGuildMailTipsWinCallback');
}
//WinCallback Functions
function SetGuildMailTipsWinCallback(event){
	let player = event.getPlayer();
	let GuildName = PlayerData[player.name].Guild;
	let Guild = isExistGuildData(GuildName);
	let index = 0;
	for (i in Guild.MailTips) {
		is = window.getEventCustomVar(event, index, "toggle") === "TRUE" ? true : false;
		if(Guild.MailTips[i] != is) {
			player.sendMessage("[NGuild] 已更改 §e"+i+"§r 为 §7"+is);
			Guild.MailTips[i] = is;
		}
		index++;
	}
	SaveGuildData(GuildName, Guild);
	sendMyGuildWin(player);
}
function MyGuildWinCallback(event){
	let player = event.getPlayer();
	let GuildName = PlayerData[player.name].Guild;
	let Guild = isExistGuildData(GuildName);
	let button = window.getEventResponseText(event);
	switch (button) {
		case '公会贡献': {
			let win = window.getCustomWindowBuilder("为公会贡献资金");
			let MaxValue = Config.GuildContriMax;
			let Contributed = Guild.GuildContriMax[player.name];
			let haveMoney = manager.getMoney(player);
			let date = Date2YMD(new Date(), 0);
			if(Guild.GuildContriMaxDate === date) {
				if(Contributed === undefined) Contributed = 0;
				MaxValue = MaxValue - Contributed;
			} else {
				Guild.GuildContriMaxDate = date;
				Guild.GuildContriMax = {};
				SaveGuildData(GuildName, Guild);
			}
			win.buildLabel("今日已贡献: §e"+Contributed+"§r/§l"+Config.GuildContriMax);
			win.buildSlider("贡献金币", 0, (haveMoney > MaxValue ? MaxValue : haveMoney), 1, 0);
			win.showToPlayer(player, 'GuildContriWinCallback');
			break;
		}
		case '公会签到': {
			if(PlayerData[player.name].SignData === undefined) PlayerData[player.name].SignData = ["2020-10-16", 0, 0];
			if(Guild.SignReward === undefined) {
				Guild.SignReward = 0;
				Guild.GuildSignDate = "2020-10-16";
				Guild.GuildSign = {};
			}
			let date = Date2YMD(new Date(), 0);
			if(date != Guild.GuildSignDate) {
				Guild.GuildSignDate = date;
				Guild.GuildSign = {};
				SaveGuildData(GuildName, Guild);
			}
			let signStatus = Guild.GuildSign[player.name];
			let subtitle = "连续签到: §l"+PlayerData[player.name].SignData[1] + "§r天 (最长"+PlayerData[player.name].SignData[2]+"天)"+
			  "\n签到奖励: "+Guild.SignReward+" 金币\n\n今日"+(signStatus ? Config.Tips.SignStatus[0] : Config.Tips.SignStatus[1])+
			  (Guild.Fund < Guild.SignReward ? "\n\n§c公会基金不足，请联系会长设置" : "");
			let win = window.getSimpleWindowBuilder("公会签到 "+date, subtitle);
			if(Guild.Fund >= Guild.SignReward && !signStatus) win.buildButton('确认', '');
			win.buildButton('取消', '');
			win.showToPlayer(player, 'GuildSignWinCallback');
			break;
			}
		case '公会商店':
			//...			break;
		case '公会事件': {
			let GuildEvent = isExistGuildEvent(GuildName);
			let win = window.getCustomWindowBuilder("公会事件列表");
			win.buildLabel("§l§7仅展示近 "+Config.GuildEventsLength+" 条");
			GuildEvent.reverse();
			for(let i = 0; i < GuildEvent.length; i++){
				win.buildLabel("§d["+GuildEvent[i][0]+"]§r "+GuildEvent[i][1]);
			}
			if(GuildEvent.length > Config.GuildEventsLength) {
				GuildEvent.length = Config.GuildEventsLength;
				GuildEvent.reverse();
				SaveGuildData(GuildName, Guild);
			}
			win.showToPlayer(player, 'GuildEventWinCallback');
			break;
		}
		case '公会成员': {
			let win = window.getCustomWindowBuilder("公会成员列表");
			let online = GuildOnlinePlayer[GuildName];
			let str = "";
			if(online) {
				str = "§l# "+Config.Posts[0]+" #§r\n"+(online.indexOf(Guild.Posts[0]) > -1 ? Config.Tips.Online[0] : Config.Tips.Online[1])+Guild.Posts[0];
				for(let i = 1; i<Guild.Posts.length; i++) {
					str += "\n\n§l# "+Config.Posts[i]+" #§r";
					for(let j = 0; j<Guild.Posts[i].length; j++) {
						let title = online.indexOf(Guild.Posts[i][j]) > -1 ? Config.Tips.Online[0] : Config.Tips.Online[1];
						str += "\n"+title+Guild.Posts[i][j];
					}
				}
			} else {
				str = "§c公会「"+GuildName+"」没有在线成员数据";
				logger.warning(GuildName);
				logger.warning(JSON.stringify(GuildOnlinePlayer));
			}
			win.buildLabel(str);
			win.showToPlayer(player, 'GuildEventWinCallback');
			break;
			}
		case '开启公会聊天':
			PlayerData[player.name].GuildChat = true;
			player.sendMessage("[NGuild] 公会聊天已开启");
			sendMyGuildWin(player);
			SavePlayerData();
			break;
		case '关闭公会聊天':
			PlayerData[player.name].GuildChat = false;
			player.sendMessage("[NGuild] 公会聊天已关闭");
			sendMyGuildWin(player);
			SavePlayerData();
			break;
		case '开启公会PVP': {
			GuildPVPData[GuildName] = true;
			Guild.GuildPVP = true;
			AddGuildEvent(GuildName, Guild, [player.name+" §6开启了公会PVP", "OpenPVP"]);
			player.sendMessage("[NGuild] 公会PVP已开启");
			sendMyGuildWin(player);
			SaveGuildData(GuildName, Guild);
			break;
			}
		case '关闭公会PVP': {
			GuildPVPData[GuildName] = false;
			Guild.GuildPVP = false;
			AddGuildEvent(GuildName, Guild, [player.name+" §f关闭了公会PVP", "ClosePVP"]);
			player.sendMessage("[NGuild] 公会PVP已关闭");
			sendMyGuildWin(player);
			SaveGuildData(GuildName, Guild);
			break;
			}
		case '传送公会基地': {
			let info = Guild.Base ? "目标世界: §c"+Guild.Base[0]+"§r\n目标位置: §6"+[Guild.Base[1], Guild.Base[2], Guild.Base[3]].join(" ") : "§c请先设置公会基地";
			let useCount = eval(Config.GuildGrade.BaseUseCount.replace("{level}", Guild.Grade));
			let subtitle = "传送基地需要消耗 "+Config.GuildBaseConfig.Use+" 公会基金"+
			  "\n\n# 基地信息 #\n"+info+"\n§r传送次数: §e"+Guild.BaseUseCount+"§r§l/"+useCount;
			let win = window.getSimpleWindowBuilder("传送公会基地", subtitle);
			if(Guild.Fund >= Config.GuildBaseConfig.Use) if(Guild.BaseUseCount < useCount) win.buildButton('确认', '');
			win.buildButton('取消', '');
			win.showToPlayer(player, 'TpGuildBaseCallback');
			break;
			}
		case '申请列表': {
			let win = window.getCustomWindowBuilder('公会申请列表');// 创建自定义窗口
			win.buildLabel("共有 "+Guild.Applicants.length+" 条申请");
			for(let i = 0; i<Guild.Applicants.length; i++){
				win.buildStepSlider(Guild.Applicants[i], "同意;无;拒绝", 1);
			}
			if(!TempVar[player.name]) TempVar[player.name] = {};
			TempVar[player.name].Applicants = Guild.Applicants;
			win.showToPlayer(player, 'ApplicantsListCallback');
			break;
		}
		case '升级公会': {
			let need = eval(Config.GuildGrade.UpgradeNeed.replace("{level}", Guild.Grade));
			let subtitle = "当前等级: "+Guild.Grade+
			  "\n当前基金: "+Guild.Fund+
			  "\n升级需要: §c"+need+"§r"+
			  "\n计算剩余: §6"+(Guild.Fund - need);
			let win = window.getSimpleWindowBuilder("升级公会", subtitle);
			if(Guild.Fund >= need) win.buildButton('确认', '');
			win.buildButton('取消', '');
			win.showToPlayer(player, 'UpgradeGuildWinCallback');
			break;
		}
		case '移除公会成员': {
			let win = window.getCustomWindowBuilder('移除公会成员');
			win.buildLabel("§7提交后即刻生效");
			let myPost = PlayerData[player.name].Post;
			if(!TempVar[player.name]) TempVar[player.name] = {};
			TempVar[player.name].DelList = [];
			for(let i = myPost+1; i<Guild.Posts.length; i++) {
				let post = Config.Posts[i];
				for(let j = 0; j<Guild.Posts[i].length; j++) {
					let title = GuildOnlinePlayer[GuildName].indexOf(Guild.Posts[i][j]) > -1 ? Config.Tips.Online[0] : Config.Tips.Online[1];
					win.buildStepSlider(title+post+"> "+Guild.Posts[i][j], "无;移除", 0);
					TempVar[player.name].DelList.push(Guild.Posts[i][j])
				}
			}
			win.showToPlayer(player, 'DelGuildMemberWinCallback');
			break;
			}
		case '设置公会简介': {
			let win = window.getCustomWindowBuilder('设置公会简介');
			win.buildLabel("§7优秀的文案能吸引更多玩家入会！");
			win.buildInput('简介', '', Guild.Introduction);
			win.showToPlayer(player, 'setIntroductionWinCallback');
			break;
			}
		case '设置公会基地': {
			let subtitle = "设置基地需要消耗 §l"+Config.GuildBaseConfig.Change+"§r 基金，往后每次传送基地需要消耗 "+Config.GuildBaseConfig.Use+" 基金"+
			  "\n\n# 基地信息 #\n当前世界: §c"+player.getLevel().getName()+"§r"+
			  "\n当前位置: §6"+[player.x.toFixed(2), player.y.toFixed(2), player.z.toFixed(2)].join(" ");
			let win = window.getSimpleWindowBuilder("设置公会基地", subtitle);
			if(!TempVar[player.name]) TempVar[player.name] = {};
			TempVar[player.name].Pos = [player.getLevel().getName(), player.x.toFixed(2), player.y.toFixed(2), player.z.toFixed(2)];
			if(Guild.Fund >= Config.GuildBaseConfig.Change) win.buildButton('确认', '');
			win.buildButton('取消', '');
			win.showToPlayer(player, 'SetGuildBaseCallback');
			break;
			}
		case '设置签到奖励':{
			let win = window.getCustomWindowBuilder('设置公会签到奖励');
			win.buildLabel("若输入框输入有误则以滑条为主");
			win.buildInput("金币", "大于0的正整数");
			win.buildSlider("金币", 0, Guild.Fund, 10);
			win.showToPlayer(player, 'SetGuildSignRewardCallback');
			break;
			}
		case '设置公会职务': {
			let win = window.getCustomWindowBuilder('设置公会成员职务');
			let mePost = PlayerData[player.name].Post;
			let items = Config.Posts.slice(mePost+1, Config.Posts.length);
			let itemStr = items.join(";");
			let list = [];
			for(let i = mePost+1; i<Guild.Posts.length; i++){
				for(let j = 0; j<Guild.Posts[i].length; j++){
					let title = GuildOnlinePlayer[GuildName].indexOf(Guild.Posts[i][j]) > -1 ? Config.Tips.Online[0] : Config.Tips.Online[1];
					win.buildStepSlider(title+Guild.Posts[i][j], itemStr, i-mePost-1);
					list.push([Guild.Posts[i][j], i])
				}
			}
			win.buildStepSlider("保存修改", "保存;取消", 0);
			if(!TempVar[player.name]) TempVar[player.name] = {};
			TempVar[player.name].GuildMemberPost = {items: items, list: list};
			win.showToPlayer(player, 'SetGuildPostCallback');
			break;
			}
		case '设置邮件提醒': {
			sendSetGuildMailTipsWin(player);
			break;
			}
		case '弹劾会长':
			//...
			break;
		case ' §r返回 ': {
			sendNGuildMainWin(player);
			break;
			}
		default:
			player.sendMessage("[NGuild] MyGuildWinCallback 未知按钮: "+button);
	}
}
function CreateGuildWinCallback(event){
	let player = event.getPlayer();
	let GuildName = window.getEventCustomVar(event, 1, "input") || false;
	if(manager.getMoney(player) < Config.CreatePrice) return player.sendMessage("[NGuild] §c您的余额不足");
	if(!Boolean(GuildName) || //new会实例化布尔值，因此这里不适用。
	  GuildName.length < Config.GuildName.LengthMin ||
	  GuildName.length > Config.GuildName.LengthMax) return player.sendMessage("[NGuild] §c公会名字长度不合法");
	if(!new RegExp(Config.GuildName.Regex).test(GuildName)) return player.sendMessage("[NGuild] §c正则校验失败");
	if(isExistGuildData(GuildName).Creator) return player.sendMessage("[NGuild] §c公会名已被占用");
	manager.reduceMoney(player, Config.CreatePrice);
	let Guild = {
		Creator: player.name,
		CreateTime: Date2YMD(new Date()),
		Introduction: "这个公会还没写介绍噢~",
		Fund: 0,
		Grade: 0,
		MaxMember: eval(Config.GuildGrade.MaxMember.replace("{level}", 0)),
		CurrentMember: 1,
		GuildPVP: false,
		Base: false,
		BaseUseCount: 0,
		Posts: [
			player.name,//会长
			[],//副会长
			[],//元老
			[],//精英
			[]//成员
		],
		MailTips: {
			switch: true,
			Applicant: true,
			Exit: true,
			Contri: true
		},
		RejectApply: {
			all: false
		},
		Applicants: [],
		GuildContriMaxDate: "2020-10-04",
		GuildContriMax: {},
		SignReward: 0,
		GuildSignDate: "2020-10-08",
		GuildSign: {}
	};
	SaveGuildAndPlayerData(GuildName, Guild);
	PlayerData[player.name] = {
		Guild: GuildName,
		GuildChat: false,
		Post: 0,
		ContriPoint: PlayerData[player.name].ContriPoint,
		SignData: ["2020-10-16", 0, 0],
		JoinTime: "2020-09-28 00:00:00", 
		JoinGameTime: Date2YMD(new Date()), 
		QuitGameTime: "2020-10-12 00:00:00"
	};
	ChangeRankValue("Member", GuildName, 1);
	ChangeRankValue("Grade", GuildName, 0);
	ChangeRankValue("Fund", GuildName, 0);
	AddGuildEvent(GuildName, Guild, [player.name+" 创立本公会", "Create"]);
	player.sendMessage("[NGuild] §a公会创建成功");
	sendMyGuildWin(player);
}
function JoinGuildWinCallback(event){
	let player = event.getPlayer();
	let button = window.getEventResponseText(event);
	switch (button) {
		case ' §c搜索公会 ':
			sendSearchGuildWin(player);
			break;
		case ' §r上一页 ':
			sendJoinGuildWin(player, TempVar[player.name].joinFromPage -1);
			break;
		case ' §r下一页 ':
			sendJoinGuildWin(player, TempVar[player.name].joinFromPage +1);
			break;
		default: {
			let res = isExistGuildData(button);
			if(res === false) {
				player.sendMessage("[NGuild] §c加入失败，该公会不存在");
				return sendJoinGuildWin(player, TempVar[player.name].joinFromPage);
			}
			if(res.RejectApply.all) {
				player.sendMessage("[NGuild] §c加入失败，该公会拒绝任何申请");
				return sendJoinGuildWin(player, TempVar[player.name].joinFromPage);
			}
			if(res.Applicants.indexOf(player.name) > -1) {
				player.sendMessage("[NGuild] §c您已向 "+button+" 公会递交过申请");
				return sendJoinGuildWin(player, TempVar[player.name].joinFromPage);
			}
			sendGuildDetailsWin(player, res, button);
		}
	}
}
function QuitGuildWinCallback(event){
	let player = event.getPlayer();
	let GuildName = PlayerData[player.name].Guild;
	let Guild = isExistGuildData(GuildName);
	switch (window.getEventCustomVar(event, 1, "stepslider")) {
		case '取消':
			sendMyGuildWin(player);
			break;
		case '退出': {
			let Post = PlayerData[player.name].Post;
			Guild.Posts[Post] = delOne(player.name, Guild.Posts[Post]);
			Guild.CurrentMember--;
			AddGuildEvent(GuildName, Guild, ["["+Config.Posts[Post]+"] "+player.name+" 退出了公会", "Exit"]);
			ChangeRankValue("Member", GuildName, Guild.CurrentMember);
			PlayerData[player.name].Guild = false;
			PlayerData[player.name].Post = -1;
			PlayerData[player.name].GuildChat = false;
			GuildOnlinePlayer[GuildName] = delOne(player.name, GuildOnlinePlayer[GuildName]);
			SaveGuildAndPlayerData(GuildName, Guild);
			sendNGuildMainWin(player);
			break;
		}
		case '转让': {
			let win = window.getSimpleWindowBuilder('转让公会 - 请选择目标', '§c§l请注意该操作不可逆');
			for(let i = 1; i<Guild.Posts.length; i++){
				for(let j = 0; j<Guild.Posts[i].length; j++) {
					let title = GuildOnlinePlayer[GuildName].indexOf(Guild.Posts[i][j]) > -1 ? Config.Tips.Online[0] : Config.Tips.Online[1];
					win.buildButton(Guild.Posts[i][j] +"\n"+ title + Config.Posts[i], "");
				}
			}
			win.buildButton(" §r取消 ", "");
			win.showToPlayer(player, 'GuildTransferCallback');
			break;
		}
		case '解散': {
			Guild.Posts[0] = [Guild.Posts[0]];
			for(let i = 0; i<Guild.Posts.length; i++){
				for(let j = 0; j<Guild.Posts[i].length; j++) {
					PlayerData[Guild.Posts[i][j]].Guild = false;
					PlayerData[Guild.Posts[i][j]].Post = -1;
					PlayerData[Guild.Posts[i][j]].GuildChat = false;
				}
			}
			ChangeRankValue("Fund", GuildName, 0, true);
			ChangeRankValue("Grade", GuildName, 0, true);
			ChangeRankValue("Member", GuildName, 0, true);
			let File = Java.type('java.io.File');
			new File('./plugins/BlocklyNukkit/NGuild/GuildData/'+GuildName+'.yml').delete();
			new File('./plugins/BlocklyNukkit/NGuild/GuildEvent/'+GuildName+'.yml').delete();
			SavePlayerData();
			GuildList = getFileList("./plugins/BlocklyNukkit/NGuild/GuildData");
			player.sendMessage("[NGuild] "+GuildName+" §a已解散");
			sendNGuildMainWin(player);
			break;
		}
	}
}
function GuildTransferCallback(event){// 转让公会回调
	let player = event.getPlayer();
	let button = window.getEventResponseText(event);
	if(button == " §r取消 ") return sendMyGuildWin(player);
	button = button.split("\n")[0];
	let GuildName = PlayerData[player.name].Guild;
	let Guild = isExistGuildData(GuildName);
	for(let i = 1; i<Guild.Posts.length; i++){
		if(Guild.Posts[i].indexOf(button) > -1) {
			Guild.Posts[i] = delOne(button, Guild.Posts[i]);
			Guild.Posts[0] = button;
			Guild.Posts[Guild.Posts.length-1].push(player.name);
			PlayerData[button].Post = 0;
			PlayerData[player.name].Post = Guild.Posts.length - 1;
			AddGuildEvent(GuildName, Guild, [player.name+" §6将公会转让给§r "+button, "Transfer"]);
			break;
		}
	}
	SaveGuildAndPlayerData(GuildName, Guild);
}
function SearchGuildWinCallback(event){// 搜索公会窗口回调
	let player = event.getPlayer();
	let input = window.getEventCustomVar(event, 0, "input") || false;
	if(input) {
		let win = window.getSimpleWindowBuilder('公会搜索结果', '');
		let list = getFileList("./plugins/BlocklyNukkit/NGuild/GuildData/");
		for(let i = 0; i<list.length; i++){
			let name = list[i].getName().split(".yml")[0];
			if(name.indexOf(input) > -1) win.buildButton(name, "");
		}
		win.buildButton(" §r返回 ", "")
		return win.showToPlayer(player, 'GuildSearchClickCallback');
	}
	sendNGuildMainWin(player);
}
function GuildSearchClickCallback(event){// 搜索公会结果点击回调
	let player = event.getPlayer();
	let button = window.getEventResponseText(event);
	if(button === " §r返回 ") return sendSearchGuildWin(player);
	sendGuildDetailsWin(player, false, button);
}
function GuildDetailsWinCallback(event){
	let player = event.getPlayer();
	let button = window.getEventCustomVar(event, 1, "stepslider");
	if(button === "申请加入") {
		let GuildName = TempVar[player.name].joinGuildName;
		let res = isExistGuildData(GuildName);
		if(res.Applicants.indexOf(player.name) > -1) player.sendMessage("[NGuild] §c你已向 "+GuildName+" 公会递交过申请");
		let coolingTime = new Date(PlayerData[player.name].joinTime).getTime()+Config.JoinCooling*1000;
		if(new Date().getTime() < coolingTime) return player.sendMessage("[NGuild] §c申请频繁，请在 "+Date2YMD(coolingTime)+" 后申请");
		res.Applicants.push(player.name);
		AddGuildEvent(GuildName, res, [player.name+" 申请加入公会", "Applicant"]);
		SaveGuildData(GuildName, res);
		player.sendMessage("[NGuild] 成功向 "+GuildName+" 公会递交申请 §7(您还可以向其它公会递交申请)");
	} else if(button === "我的工会") {
		return sendMyGuildWin(player);
	}
	manager.setTimeout(function (){
		sendNGuildMainWin(player);
	}, 10);
}
function UpgradeGuildWinCallback(event){
	let player = event.getPlayer();
	let button = window.getEventResponseText(event);
	if(button === "确认") {
		let GuildName = PlayerData[player.name].Guild;
		let Guild = isExistGuildData(GuildName);
		let need = eval(Config.GuildGrade.UpgradeNeed.replace("{level}", Guild.Grade));
		if(Guild.Fund < need) {
			player.sendMessage("[NGuild] §c基金不足，还需要§f"+need-Guild.Fund+"§r");
		} else {
			Guild.Grade++;
			Guild.MaxMember = eval(Config.GuildGrade.MaxMember.replace("{level}", Guild.Grade));
			Guild.Fund = Guild.Fund - need;
			AddGuildEvent(GuildName, Guild, [player.name+" §6消耗§r "+need+" 公会基金用于升级公会", "Upgrade"]);
			ChangeRankValue("Fund", GuildName, Guild.Fund);
			ChangeRankValue("Grade", GuildName, Guild.Grade);
			SaveGuildData(GuildName, Guild);
		}
	}
	sendMyGuildWin(player);
}
function DelGuildMemberWinCallback(event){
	let player = event.getPlayer();
	let GuildName = PlayerData[player.name].Guild;
	let Guild = isExistGuildData(GuildName);
	let GuildEvent = isExistGuildEvent(GuildName);
	let list = TempVar[player.name].DelList;
	for(let i = 0; i<list.length; i++){
		if(window.getEventCustomVar(event, i+1, "stepslider") === "移除") {
			if(PlayerData[list[i]].Guild === false) continue;
			Guild.Posts[PlayerData[list[i]].Post] = delOne(list[i], Guild.Posts[PlayerData[list[i]].Post]);
			Guild.CurrentMember --;
			GuildEvent.push([Date2YMD(new Date()), player.name+" §c移除 §f"+Config.Posts[PlayerData[list[i]].Post]+"§r "+list[i]]);
			GuildOnlinePlayer[GuildName] = delOne(list[i], GuildOnlinePlayer[GuildName]);
			PlayerData[list[i]].Guild = false;
			PlayerData[list[i]].Post = -1;
			PlayerData[list[i]].GuildChat = false;
			player.sendMessage("[NGuild] 已移除 "+list[i]+".");
		}
	}
	ChangeRankValue("Member", GuildName, Guild.CurrentMember);
	SaveGuildAndPlayerData(GuildName, Guild);
	SaveGuildEvent(GuildName, GuildEvent);
}
function setIntroductionWinCallback(event){
	let player = event.getPlayer();
	let GuildName = PlayerData[player.name].Guild;
	let Guild = isExistGuildData(GuildName);
	let input = window.getEventCustomVar(event, 1, "input");
	if(input != Guild.Introduction) {
		Guild.Introduction = input;
		AddGuildEvent(GuildName, Guild, [player.name+" §6修改§r 了公会简介", "Introduction"]);
		player.sendMessage("[NGuild] 公会简介已修改.");
		sendNGuildMainWin(player);
		SaveGuildData(GuildName, Guild);
	}
	sendMyGuildWin(player);
}
function SetGuildBaseCallback(event){
	let player = event.getPlayer();
	let button = window.getEventResponseText(event);
	if(button != "确认") return sendMyGuildWin(player);
	let GuildName = PlayerData[player.name].Guild;
	let Guild = isExistGuildData(GuildName);
	if(Guild.Fund < Config.GuildBaseConfig.Change) {
		player.sendMessage("[NGuild] §c操作失败，公会基金不足");
		return sendMyGuildWin(player);
	}
	Guild.Base = TempVar[player.name].Pos;
	Guild.BaseUseCount = 0;
	Guild.Fund -= Config.GuildBaseConfig.Change;
	AddGuildEvent(GuildName, Guild, [player.name+" §6消耗§r "+Config.GuildBaseConfig.Change+" 公会基金设置§2 "+Guild.Base.join(" ")+" §r为公会基地", "GuildBase"]);
	SaveGuildData(GuildName, Guild);
	player.sendMessage("[NGuild] 公会基地设置成功");
	ChangeRankValue("Fund", GuildName, Guild.Fund);
}
function SetGuildSignRewardCallback(event){
	let player = event.getPlayer();
	let GuildName = PlayerData[player.name].Guild;
	let input = Math.ceil(Number(window.getEventCustomVar(event, 1, "input")));
	let value = 0;
	input > 0 ? value = input : value = window.getEventCustomVar(event, 2, "slider");
	if(value === 0) return sendMyGuildWin(player);
	let Guild = isExistGuildData(GuildName);
	if(value === Guild.SignReward) return sendMyGuildWin(player);
	if(Guild.Fund < value) {
		player.sendMessage("[NGuild] 签到奖励不得小于"+Guild.Fund);
		manager.setTimeout(function(player) {
			sendMyGuildWin(player)
		}, 20, player);
	}
	Guild.SignReward = value;
	AddGuildEvent(GuildName, Guild, [player.name+" 设置公会签到奖励为 "+value, "SetSignReward"]);
	SaveGuildData(GuildName, Guild);
	player.sendMessage("[NGuild] 成功设置公会签到奖励为 "+value);
	manager.setTimeout(function(player) {
		sendMyGuildWin(player)
	}, 20, player);
}
function SetGuildPostCallback(event){
	let player = event.getPlayer();
	let data = TempVar[player.name].GuildMemberPost;
	if(window.getEventCustomVar(event, data.list.length, "stepslider") === "取消") return sendMyGuildWin(player);
	if(data.post > PlayerData[player.name].Post) {
		player.sendMessage("[NGuild] §c无权更改，因为您的职务发生变更");
		return sendMyGuildWin(player);
	}
	let GuildName = PlayerData[player.name].Guild;
	let Guild = isExistGuildData(GuildName);
	let GuildEvent = isExistGuildEvent(GuildName);
	let addEvent = "";
	for(let i = 0; i<data.list.length; i++){
		let select = window.getEventCustomVar(event, i, "stepslider");
		let i1 = data.list[i][1];
		let i2 = Config.Posts.indexOf(select);
		if(i1 === i2) continue;
		Guild.Posts[i1] = delOne(data.list[i][0], Guild.Posts[i1]);
		Guild.Posts[i2].push(data.list[i][0]);
		addEvent += data.list[i][0]+", "+Config.Posts[i1]+", "+select;
		PlayerData[data.list[i][0]].Post = i2;
		player.sendMessage("[NGuild] 你修改 ["+Config.Posts[i1]+"]"+data.list[i][0]+" 的职位为"+select);
	}
	if(addEvent != "") {
		GuildEvent.push([Date2YMD(new Date()), player.name+" §6更改了部分成员职位§r\n§7名字, 原职位, 新职位§r\n"+addEvent]);
		SaveGuildAndPlayerData(GuildName, Guild);
		SaveGuildEvent(GuildName, GuildEvent)
	}
	delete TempVar[player.name];
	sendMyGuildWin(player);
}
function TpGuildBaseCallback(event){
	let player = event.getPlayer();
	let button = window.getEventResponseText(event);
	if(button != "确认") return sendMyGuildWin(player);
	let GuildName = PlayerData[player.name].Guild;
	let Guild = isExistGuildData(GuildName);
	if(Guild.Base === false) {
		player.sendMessage("[Guild] §c本公会没有设置公会基地");
		return sendMyGuildWin(player);
	}
	if(Guild.Fund < Config.GuildBaseConfig.Use) {
		player.sendMessage("[NGuild] §c操作失败，公会基金不足");
		return sendMyGuildWin(player);
	}
	Guild.BaseUseCount ++;
	Guild.Fund -= Config.GuildBaseConfig.Use;
	AddGuildEvent(GuildName, Guild, [player.name+" §6消耗§r "+Config.GuildBaseConfig.Use+" 公会基金传送至公会基地", "UseGuildBase"]);
	SaveGuildData(GuildName, Guild);
	ChangeRankValue("Fund", GuildName, Guild.Fund);
	player.sendMessage("[NGuild] 成功传送至公会基地");
	player.teleport(Java.type("cn.nukkit.level.Position").fromObject(manager.buildvec3(Guild.Base[1], Guild.Base[2], Guild.Base[3]), server.getLevelByName(Guild.Base[0])));
}
//MyGuildWin Fork Functions
function ApplicantsListCallback(event){
	let player = event.getPlayer();
	let GuildName = PlayerData[player.name].Guild;
	let Guild = isExistGuildData(GuildName);
	let GuildEvent = isExistGuildEvent(GuildName);
	let list = TempVar[player.name].Applicants;
	let isChange = false;
	f1:
	for(let i = 0; i<list.length; i++) {
		switch (window.getEventCustomVar(event, i+1, "stepslider")) {
		case '同意':
			isChange = true;
			if(Guild.CurrentMember >= Guild.MaxMember) {
				player.sendMessage("[NGuild] §c公会人数已满，请先提升公会等级！");
				break f1;
			}
			if(PlayerData[list[i]].Guild != false) {
				player.sendMessage("[NGuild] §7"+list[i]+" 已加入其它公会("+PlayerData[list[i]].Guild+")");
				Guild.Applicants = delOne(list[i], Guild.Applicants);
				continue;
			}
			player.sendMessage("[NGuild] §7你同意了 "+list[i]+" 的入会申请");

			GuildEvent.push([Date2YMD(new Date()), player.name+" §a同意§r 了 "+list[i]+" 的入会申请"]);
			Guild.Applicants = delOne(list[i], Guild.Applicants);
			Guild.CurrentMember++;
			Guild.Posts[4].push(list[i]);
			PlayerData[list[i]].Guild = GuildName;
			PlayerData[list[i]].Post = 4;
			PlayerData[list[i]].JoinTime = Date2YMD(new Date());
			GuildOnlinePlayer[GuildName].push(list[i]);
			let playerData = manager.callFunction("PlayerLogin.js::getPlayerData", list[i], true);
			if(playerData && playerData.email){
				manager.runThread(F(function(){manager.callFunction("NSendMail", playerData.email, 'RPG - 乱世曙光', player.name+' 同意了您的入会申请<br />简介：'+Guild.Introduction, 'Guild', list[i])}));
			}
			break;
		case '拒绝':
			isChange = true;
			player.sendMessage("[NGuild] §7你拒绝了 "+list[i]+" 的入会申请");
			GuildEvent.push([Date2YMD(new Date()), player.name+" §c拒绝§r 了 "+list[i]+" 的入会申请"]);
			Guild.Applicants = delOne(list[i], Guild.Applicants);
			break;
		}
	}
	if(isChange) {
		ChangeRankValue("Member", GuildName, Guild.CurrentMember);
		SaveGuildAndPlayerData(GuildName, Guild);
		SaveGuildEvent(GuildName, GuildEvent);
	}
	delete TempVar[player.name];
	sendMyGuildWin(player);
}
function GuildContriWinCallback(event){
	let player = event.getPlayer();
	let GuildName = PlayerData[player.name].Guild;
	let Guild = isExistGuildData(GuildName);
	let value = Math.round(window.getEventCustomVar(event, 1, "slider"));
	if(value === 0) return sendMyGuildWin(player);
	if(value > manager.getMoney(player)) return player.sendMessage("[NGuild] 你没有足够§7("+value+")§r的经济进行捐赠");
	if(Guild.GuildContriMax[player.name] === undefined) Guild.GuildContriMax[player.name] = 0;
	manager.reduceMoney(player, value);
	Guild.Fund += new Number(value);
	Guild.GuildContriMax[player.name] += new Number(value);
	AddGuildEvent(GuildName, Guild, [player.name+" 为公会§a捐赠§r 了 "+value+" 经济", "Contri"]);
	ChangeRankValue("Fund", GuildName, Guild.Fund);
	SaveGuildData(GuildName, Guild);
	player.sendMessage("[NGuild] 你成功向公会捐赠了"+value);
	sendMyGuildWin(player);
}
function GuildSignWinCallback(event){
	let player = event.getPlayer();
	let name = player.name;
	let button = window.getEventResponseText(event);
	if(button != "确认") return sendMyGuildWin(player);
	let GuildName = PlayerData[name].Guild;
	let Guild = isExistGuildData(GuildName);
	if(Guild.Fund < Guild.SignReward) return player.sendMessage("[NGuild] §c签到失败，当前公会基金不足");
	Guild.Fund -= Guild.SignReward;
	Guild.GuildSign[name] = true;
	manager.addMoney(player, Guild.SignReward);
	player.sendMessage("[NGuild] 签到成功，获得了 §a"+Guild.SignReward+" §f签到奖励");
	let d = Date2YMD(new Date(), 0);
	if(Date2YMD(new Date(new Date().getTime() - 86400000), 0) === PlayerData[name].SignData[0]) {
		PlayerData[name].SignData[1] ++;
	} else {
		PlayerData[name].SignData[1] = 1;
	}
	if(PlayerData[name].SignData[0] != d) PlayerData[name].SignData[0] = d;
	if(PlayerData[name].SignData[1] > PlayerData[name].SignData[2]) {
		PlayerData[name].SignData[2] = PlayerData[player.name].SignData[1];
		player.sendMessage("[NGuild] §2恭喜历史连续签到创下新纪录 §a§l"+PlayerData[name].SignData[1]+" §r§2天");
	}
	AddGuildEvent(GuildName, Guild, [name+" 连续 "+PlayerData[name].SignData[1]+" 天签到成功获得 "+Guild.SignReward+" 公会基金", "Sign"]);
	SaveGuildAndPlayerData(GuildName, Guild);
}
function GuildEventWinCallback(event){
	sendMyGuildWin(event.getPlayer());
}

//Other Functions
function Date2YMD(t, mode){
	let d = [[t.getFullYear(), FormatZero(t.getMonth()+1, 2), FormatZero(t.getDate(), 2)].join("-"), FormatZero(t.getHours(), 2)+':'+FormatZero(t.getMinutes(), 2)+':'+FormatZero(t.getSeconds(), 2)];
	return mode != undefined ? d[mode] : d.join(" ");
}
function FormatZero(num, len) {
	if(new String(num).length > len) return num;
	return (new Array(len).join(0) + num).slice(-len);
}
function getFileList(path){// 获取路径下文件数量
	let File = Java.type('java.io.File');
	return new File(path).listFiles();
}
function isExistGuildData(GuildName){
	let content = manager.readFile('./plugins/BlocklyNukkit/NGuild/GuildData/'+GuildName+'.yml');
	if(content == "FILE NOT FOUND") {
		return {};
	} else {
		return JSON.parse(manager.YAMLtoJSON(content));
	}
}
function isExistGuildEvent(GuildName){
	let content = manager.readFile('./plugins/BlocklyNukkit/NGuild/GuildEvent/'+GuildName+'.yml');
	if(content == "FILE NOT FOUND") {
		SaveGuildEvent(GuildName, []);
		return [];
	} else {
		return JSON.parse(content);
	}
}
function isExistDir(path){
	let File = Java.type('java.io.File');
	dir = new File(path);
	if (!dir.exists()) {// 判断目录是否存在
		dir.mkdir();
	}
}
function delOne(str, arr){// 删除数组指定元素
	let index = arr.indexOf(str);
	if(index != -1) arr.splice(index, 1);
	return arr;
}
function getGuildName(player){
	if(PlayerData[player.name] === undefined) return Config.Tips.NoneGuild;
	return PlayerData[player.name].Guild || Config.Tips.NoneGuild;
}
function getGuildPost(player){
	if(PlayerData[player.name] === undefined) return Config.Tips.NoneGuild;
	return PlayerData[player.name].Post < 0 ? Config.Tips.NoneGuild : PlayerData[player.name].Post;
}
window.makeTipsVar("{NGuildName}", "getGuildName");
window.makeTipsVar("{NGuildPost}", "getGuildPost");

// 排行榜数据更新算法
function compare(porp){
	return function(a, b){
		var v1 = a[porp];
		var v2 = b[porp];
		return v2 - v1;
	}
}
function ChangeRankValue(type, name, value, del){
	let index = GuildRankData[type].length;
	for(let i = 0; i < GuildRankData[type].length; i++) {
		if(GuildRankData[type][i].name === name) {
			index = i;
			break;
		}
	}
	if(del === true) {
		GuildRankData[type].splice(index, 1);
	} else {
		GuildRankData[type][index] = {name: name, value: value};
		GuildRankData[type].sort(compare("value"));
	}
	manager.writeFile('./plugins/BlocklyNukkit/NGuild/GuildRankData.json', JSON.stringify(GuildRankData));
}

// Guild Chat
function PlayerChatEvent(event){
	let name = event.getPlayer().getName();
	if(PlayerData[name] === undefined) return;
	let msg = event.getMessage();
	let GuildName = PlayerData[name].Guild;
	if(Config.GuildChat === false) return;
	if(PlayerData[name].GuildChat) {
		for(let i = 0; i<GuildOnlinePlayer[GuildName].length; i++){
			let toPlayer = server.getPlayer(GuildOnlinePlayer[GuildName][i]);
			toPlayer.sendMessage(Config.GuildChatConfig.style
			  .replace("{post}", Config.Posts[PlayerData[name].Post])
			  .replace("{name}", name)
			  .replace("{msg}", msg));
		}
		event.setCancelled();
	}
}

// All Guild Online Player
var GuildOnlinePlayer = {};
function PlayerJoinEvent(event){
	let name = event.getPlayer().getName();
	if(PlayerData[name] === undefined) return;
	let GuildName = PlayerData[name].Guild;
	if(GuildName != false) {
		PlayerData[name].JoinGameTime = Date2YMD(new Date());
		SavePlayerData();
		if(!GuildOnlinePlayer[GuildName]) GuildOnlinePlayer[GuildName] = [];
		GuildOnlinePlayer[GuildName].push(name);
	}
}
function PlayerQuitEvent(event){
	let name = event.getPlayer().getName();
	if(PlayerData[name] === undefined) return;
	let GuildName = PlayerData[name].Guild;
	if(GuildName != false) {
		PlayerData[name].QuitGameTime = Date2YMD(new Date());
		SavePlayerData();
		if(GuildOnlinePlayer[GuildName] === undefined) return;
		GuildOnlinePlayer[GuildName] = delOne(name, GuildOnlinePlayer[GuildName]);
	}
}

//Cheak Guild PVP Status
var GuildPVPData = {};
function getGuildPVPStatus(GuildName){
	if(GuildPVPData[GuildName] === undefined){
		let Guild = isExistGuildData(GuildName);
		GuildPVPData[GuildName] = Guild.GuildPVP;
	}
	return GuildPVPData[GuildName];
}
function EntityDamageByEntityEvent(event){
	let Damager = event.getDamager();//攻击者
	let Wounded = event.getEntity();//被攻击者
	if(!isPlayer(Damager)||!isPlayer(Wounded)) return;
	if(PlayerData[Damager.name] === undefined) return;
	if(PlayerData[Wounded.name] === undefined) return;
	let DamagerGuild = PlayerData[Damager.name].Guild;
	if(DamagerGuild === PlayerData[Wounded.name].Guild) {
		if(!getGuildPVPStatus(DamagerGuild)) {
			Damager.sendPopup(Config.Tips.NotAllowGuildPVP);
			event.setCancelled();
		}
	}
}
function isPlayer(entity) {
	return entity instanceof Java.type("cn.nukkit.Player");
}

// Data Save
function AddGuildEvent(GuildName, Guild, data){
	let GuildEvent = isExistGuildEvent(GuildName);
	GuildEvent.push([Date2YMD(new Date()), data[0]]);
	if(Guild.MailTips && Guild.MailTips.switch && Guild.MailTips[data[1]]){
		// Guild of Send Mail Tips
		let index = Config.MailTips[data[1]] || 0;
		for (; index > -1; index--) {
			let arr = [];
			if(index === 0) {
				arr = [Guild.Posts[index]];
			} else {
				arr = JSON.parse(JSON.stringify(Guild.Posts[index]))
			}
			arr.forEach(function(name){
				let playerData = manager.callFunction("PlayerLogin.js::getPlayerData", name, true);
				if(playerData && playerData.email){
					manager.runThread(F(function(){manager.callFunction("NSendMail", playerData.email, 'RPG - 乱世曙光', '# 公会事件 #<br />'+data[0].replace(/§./g, ""), 'Guild', name)}));
				}
			})
		}
	}
	if(GuildEvent.length > Config.GuildEventsLength) {
		GuildEvent.reverse();
		GuildEvent.length = Config.GuildEventsLength - 5;
		GuildEvent.reverse();
	}
	manager.writeFile('./plugins/BlocklyNukkit/NGuild/GuildEvent/'+GuildName+'.yml', JSON.stringify(GuildEvent));
}
function SaveGuildEvent(GuildName, data){
	manager.writeFile('./plugins/BlocklyNukkit/NGuild/GuildEvent/'+GuildName+'.yml', JSON.stringify(data));
}
function SaveGuildData(GuildName, data){
	manager.writeFile('./plugins/BlocklyNukkit/NGuild/GuildData/'+GuildName+'.yml', manager.JSONtoYAML(JSON.stringify(data)));
}
function SavePlayerData(){
	manager.writeFile('./plugins/BlocklyNukkit/NGuild/PlayerData.yml', manager.JSONtoYAML(JSON.stringify(PlayerData)));
}
function SaveGuildAndPlayerData(GuildName, Guild){
	SaveGuildData(GuildName, Guild);
	SavePlayerData();
}
